﻿#include "fb_additem.h"
#include "ui_fb_additem.h"

FB_AddItem::FB_AddItem(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::FB_AddItem)
{
    ui->setupUi(this);

    table=TD_FEEDBACK;
    ui->dateEdit->setDate(QDate::currentDate());
    updateTopic();
}

FB_AddItem::~FB_AddItem()
{
    delete ui;
}

void FB_AddItem::updateTopic()
{
    QStringList items=sp_getCategory(table);
    if(!items.isEmpty())
        ui->topics->addItems(items);

    ui->topics->addItem(MANUAL_INPUT);
    ui->topics->setCurrentIndex(-1);
}

void FB_AddItem::on_topics_currentTextChanged(const QString &text)
{
    if(text == MANUAL_INPUT)
    {
        ui->topic->clear();
        ui->topic->setEnabled(true);
    }
    else
    {
        ui->topic->setText(text);
        ui->topic->setEnabled(false);
    }
}

void FB_AddItem::setTopic(const QString &topic)
{
    ui->topics->setCurrentText(topic);
}

bool FB_AddItem::addItem(const QString &topic,
                         const QString &detail)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (month_,date_,category,detail) "
                          "values (?,?,?,?)")
                  .arg(table));
    query.addBindValue(CurrentMonth);
    query.addBindValue(ui->dateEdit->date().toString(DATE_FORMAT));
    query.addBindValue(topic);
    query.addBindValue(detail);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void FB_AddItem::on_btn_submit_clicked()
{
    QString topic=ui->topic->text().trimmed();
    if(topic.isEmpty())
    {
        MESSAGE_CATEGORY_EMPTY
    }

    QString detail=ui->detail->toPlainText().trimmed();
    if(detail.isEmpty())
    {
        MESSAGE_DETAIL_EMPTY
    }

    QString summary;
    QString customer=ui->customer->text().trimmed();
    if(!customer.isEmpty())
    {
        customer=QStringLiteral("【") + customer + QStringLiteral("】");
        summary = customer;
    }

    QString express=ui->express->text().trimmed();
    if(!express.isEmpty())
    {
        express=QStringLiteral("（") + express + QStringLiteral("）");
        summary=summary + express;
    }

    if(!summary.isEmpty())
        detail=summary + detail;

    if(addItem(topic,detail))
        accept();
    else
        MESSAGE_CANNOT_SUBMIT
}
